package com.apimanage.gateway.handler;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关全局异常处理类
 * 捕获和处理网关中的异常
 */
@Component
@Order(-2)
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> errorResponse = new HashMap<>();

        // 根据异常类型设置响应状态码和错误信息
        if (ex instanceof ResponseStatusException) {
            ResponseStatusException statusException = (ResponseStatusException) ex;
            response.setStatusCode(statusException.getStatusCode());
            errorResponse.put("code", statusException.getStatusCode().value());
            errorResponse.put("message", statusException.getReason());
        } else if (ex instanceof NotFoundException) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            errorResponse.put("code", 404);
            errorResponse.put("message", "请求的资源不存在");
        } else if (ex instanceof IllegalArgumentException) {
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            errorResponse.put("code", 400);
            errorResponse.put("message", ex.getMessage());
        } else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器内部错误");
        }

        // 添加异常详情（开发环境可以显示，生产环境应关闭）
        errorResponse.put("errorDetail", ex.getMessage());

        // 将错误响应写入响应体
        DataBufferFactory bufferFactory = response.bufferFactory();
        String errorJson = "{\"code\":\"" + errorResponse.get("code") + "\",\"message\":\"" +
                errorResponse.get("message") + "\",\"errorDetail\":\"" + errorResponse.get("errorDetail") + "\"}";
        return response.writeWith(Mono.just(bufferFactory.wrap(errorJson.getBytes())));
    }

}